package me.boot.db.mybatis.interceptor.tablename;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import me.boot.gen.table.StarupMode;
import me.boot.gen.table.TableGenerator;

@Slf4j
public abstract class BaseTableNameHandler implements TableNameHandler {

    @Setter
    protected boolean autoCreateTable;

    @Override
    public String dynamicTableName(String sql, String tableName) {
        String dynamicTable = getDynamicTableName(sql, tableName);
        if (!TableGenerator.existTable(dynamicTable)) {
            autoCreate(tableName, dynamicTable);
        }

        return dynamicTable;
    }

    protected String getDynamicTableName(String sql, String tableName) {
        return tableName;
    }

    protected void autoCreate(String tableName, String newTableName) {
        TableInfo tableInfo = TableInfoHelper.getTableInfo(tableName);
        Assert.notNull(tableInfo, "tableInfo not found:" + tableName);
        Class<?> entityClass = tableInfo.getEntityType();

        if (!autoCreateTable) {
            log.error(StrUtil.format("未开启自动创建动态表，请提前手工创建。 动态表:{}", tableName));
        } else {
            TableGenerator.generateTable(StarupMode.Create, entityClass, newTableName);
        }
    }


}
